package com.exahq.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.exahq.common.dto.AdminLoginDto;
import com.exahq.common.lang.Result;
import com.exahq.entity.Admin;
import com.exahq.entity.Loginlog;
import com.exahq.entity.Viwe;
import com.exahq.service.AdminService;
import com.exahq.service.LoginlogService;
import com.exahq.service.ViweService;
import com.exahq.util.JwtUtils;
import com.exahq.util.UtilsIp;
import com.sun.xml.internal.xsom.impl.scd.Iterators;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:管理员登录
 * @author: lhq
 * @time: 2021/1/27 19:48
 */
@RestController
public class AdminLoginController {
        @Autowired
        JwtUtils jwtUtils;
        @Autowired
        AdminService adminService;
        @Autowired
        LoginlogService loginlogService; //登录记录
        @Autowired
        ViweService viweService; //用户访问数据
        /**
         * 登录
         * @param loginDto
         * @param response
         * @return
         */
        @CrossOrigin
        @RequestMapping(value = "/adminLogin", method = RequestMethod.POST)
        @ResponseBody
        public Result login(@Validated @RequestBody AdminLoginDto loginDto, HttpServletResponse response, HttpServletRequest request) throws Exception {
            Admin admin = adminService.getOne(new QueryWrapper<Admin>().eq("aName", loginDto.getAName()));
            Assert.notNull(admin, "用户不存在");
            if(!admin.getAPassword().equals(SecureUtil.md5(loginDto.getAPassword()))) {
                return Result.fail("密码错误！");
            }
            String jwt = jwtUtils.generateToken(admin.getId());
            response.setHeader("Authorization", jwt);
            response.setHeader("Access-Control-Expose-Headers", "Authorization");
            //登录记录
            Loginlog loginlog=loginlogService.getOneId(admin.getId());
            Loginlog temp =new Loginlog();
            if (!UtilsIp.getAddrName(UtilsIp.getIpAddr(request)).trim().equals("")){
                temp.setAddress(UtilsIp.getAddrName(UtilsIp.getIpAddr(request)));
            }else {
                temp.setAddress(UtilsIp.getAddrName("梧州市"));
            }
            temp.setLoginDate(new Date());
            temp.setIp(UtilsIp.getIpAddr(request));
            temp.setUid(admin.getId());
            BeanUtil.copyProperties(loginlog,temp, "id", "address", "loginDate", "ip","uid");
            loginlogService.save(temp);
            // 用户可以另一个接口
            return Result.succ(MapUtil.builder()
                    .put("id", admin.getId())
                    .put("aName", admin.getAName())
                    .put("aPassword", admin.getAPassword())
                    .put("state", admin.getState())
                    .put("delFlag", admin.getDelFlag())
                    .put("loginlog",loginlog)
                    .map()
            );

        }

        // 退出
        @RequiresAuthentication
        @GetMapping("/adminLogout")
        public Result logout() {
            System.out.println("jfkfjkj");
            SecurityUtils.getSubject().logout();
            return Result.succ(null);
        }

   @RequestMapping("/indexData/{id}")
   @RequiresAuthentication
    public Result indexData(HttpServletRequest request,@PathVariable(name = "id") Integer id){
       Viwe viwe = viweService.getById(id);
       Map<String,String> map = new HashMap<String,String>() ;
       return Result.succ(null);
   }

    }
